<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="userName">
              <el-input v-model="searchForm.userName" :clearable="true" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="nickName">
              <el-input v-model="searchForm.nickName" :clearable="true" placeholder="用户昵称"></el-input>
            </el-form-item>
            <el-form-item prop="userCode">
              <el-input v-model="searchForm.userCode" :clearable="true" placeholder="用户编号"></el-input>
            </el-form-item>
            <el-form-item prop="userId">
              <el-input v-model="searchForm.userId" :clearable="true" placeholder="用户ID"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="searchForm.phone" :clearable="true" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="customerLevels">
              <el-select v-model="searchForm.customerLevels" :clearable="true" placeholder="请选择用户角色">
                <el-option key="1" label="普通用户" :value="1"></el-option>
                <el-option key="2" label="推广员" :value="2"></el-option>
                <el-option key="3" label="业务员" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input style="width: 120px" v-model="searchForm.minHealthPoints" :clearable="true" placeholder="最小积分值"></el-input> -
              <el-input style="width: 120px" v-model="searchForm.maxHealthPoints" :clearable="true" placeholder="最大积分值"></el-input>
            </el-form-item>
            <el-form-item prop="villageId">
              <el-select v-model="searchForm.villageId" clearable remote :remote-method="getVillageList" filterable placeholder="请选择小区">
                <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table ref="tableList" :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <!--<el-table-column  prop="userId" label="用户ID" width="150" align="center"></el-table-column>-->
        <el-table-column label="头像" width="120" align="center">
          <template slot-scope="scope">
            <el-image fit="cover" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"> </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="userCode" label="用户编号" width="150" align="center"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="150" align="center"></el-table-column>
        <el-table-column prop="nickName" label="用户昵称" width="150" align="center"></el-table-column>
        <el-table-column label="用户角色" align="center" width="120">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatUserRoles(scope.row.customerLevels)">
                {{ formatUserRole(scope.row.customerLevels) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="fullName" label="真实姓名" width="100" align="center"></el-table-column>
        <el-table-column label="性别" width="60" align="center">
          <template slot-scope="scope">
            <div>
              {{ scope.row.sex === 1 ? '男' : '女' }}
            </div>
          </template>
        </el-table-column>
        <!--<el-table-column prop="email" label="邮箱" width="200" align="center"></el-table-column>-->
        <el-table-column prop="phone" label="手机号码" width="120" align="center"></el-table-column>
        <el-table-column prop="openId" label="微信小程序openId" width="130" align="center"></el-table-column>
        <el-table-column prop="healthPoints" label="积分数" width="80" align="center"></el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="150" align="center"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <!-- <el-dropdown-item v-has="permissionEdit"
                    @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item> -->
                  <el-dropdown-item v-has="permissionCashSet" v-if="scope.row.customerLevels == 2" @click.native="handleCashSet(scope.row)">提现设置</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state === 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                  <el-dropdown-item v-has="permissionIntegral" @click.native="handleClickSetIntegral(scope.row)">积分修改</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
    <!-- 提现设置 -->
    <CashSet :show.sync="cashSet.show" :info="cashSet.info" @confirm="confirmCashSet"></CashSet>
    <el-dialog title="修改积分" :visible.sync="integralShow" width="30%" :before-close="handleCloseIntegral">
      <div class="m-b-10">
        <el-row>
          <el-col :span="12">当前积分：{{ oldIntegralNum }}</el-col>
          <el-col :span="12">修改后的积分：{{ countIntegral }}</el-col>
        </el-row>
      </div>
      <div class="m-b-10">
        <el-input-number ref="refNumber" v-model="integralNum" @change="integralBlur" :step="1" label=""></el-input-number>
      </div>
      <div class="m-b-10">
        <el-input type="textarea" :rows="2" placeholder="积分变动说明" v-model="integralRemark"> </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseIntegral">取 消</el-button>
        <el-button type="primary" @click="handleConfirmIntegral">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CashSet from '../../components/CashSet.vue';
import * as message from '@/constants/message';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import AuthApi from '@/api/system/auth';
import CustomerApi from '@/api/customer/customer';
import AccountInfoApi from '@/api/account/accountInfo';
import VillageApi from '@/api/address/village';

export default {
  name: 'CustomerManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      searchForm: {
        userName: '',
        nickName: '',
        userCode: '',
        userId: this.$route.query.userId || '',
        phone: '',
        customerLevels: '',
        state: '',
        minHealthPoints: '',
        maxHealthPoints: '',
        villageId: '',
      },
      id: 0,
      integralShow: false,
      integralNum: 0,
      oldIntegralNum: 0,
      integralRemark: '',
      tableList: [],
      villageList: [],

      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      permissionCheck: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_DELETE',
      permissionCashSet: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_CASHSET',
      permissionIntegral: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_INTEGRAL',
      magRegion: {
        show: false,
        list: [],
        relationId: '',
      },
      cashSet: {
        show: false,
        info: {
          cashType: '',
          settleType: '',
          settleDay: '',
          cashDay: 1,
          userType: 3,
        },
      },
      rowItem: null,
    };
  },
  computed: {
    countIntegral() {
      let newVal = 0;
      if (this.integralNum >= 0) {
        newVal = this.oldIntegralNum + this.integralNum;
      } else {
        newVal = this.oldIntegralNum - Math.abs(this.integralNum);
      }
      if (newVal < 0) {
        this.$message.error('修改后的积分不能小于0');
        this.$nextTick(() => {
          this.integralNum = -this.oldIntegralNum;
        });
        return (newVal = -this.oldIntegralNum);
      } else {
        return newVal;
      }
    },
  },
  components: {
    CashSet,
  },
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    const { userId } = this.$route.query;
    if (userId) {
      this.searchForm.userId = userId;
      this.init();
    }
    if (this.$route.meta.keepAlive) {
      this.listData();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listData();
      this.getTableHeight();
      // this.getVillageList();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    formatTime(row, column, cellValue) {
      return this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatSex(row, column, cellValue) {
      return cellValue === 1 ? '男' : '女';
    },
    formatUserRole(cellValue) {
      if (cellValue === 1) {
        return '普通用户';
      } else if (cellValue === 2) {
        return '推广员';
      } else if (cellValue === 3) {
        return '业务员';
      }
    },
    formatUserRoles(cellValue) {
      if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return 'warning';
      } else if (cellValue === 3) {
        return '';
      }
    },
    formatState(cellValue) {
      if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === 0) {
        return 'warning';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    listData() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        ...this.searchForm,
      };
      CustomerApi.listCustomer(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.$refs.tableList.bodyWrapper.scrollTop = 0;
        })
        .catch((error) => {});
    },
    async getVillageList(query) {
      console.log(query);
      if (query !== '') {
        const { data } = await VillageApi.villageList({ name: query });
        setTimeout(() => {
          this.villageList = data || [];
        }, 500);
      }
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listData();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listData();
    },
    handleClickSetIntegral(row) {
      this.id = row.customerId;
      this.oldIntegralNum = row.healthPoints;
      this.integralShow = true;
    },
    handleCloseIntegral() {
      this.integralShow = false;
      this.integralNum = 0;
      this.id = 0;
      this.integralRemark = '';
      this.oldIntegralNum = 0;
    },
    handleConfirmIntegral() {
      if (this.integralNum == 0) {
        this.$message.error('不允许输入0');
        return false;
      }
      CustomerApi.setIntegral({
        customerId: this.id,
        content: this.integralRemark,
        healthPoints: this.integralNum,
      }).then((res) => {
        if (res.status == 0) {
          this.$message.success('操作成功');
          this.listData();
          this.handleCloseIntegral();
        }
      });
    },
    integralBlur(val) {
      if (!Number.isInteger(this.integralNum)) {
        this.$message.error('请输入整数');
        this.$nextTick(() => {
          this.integralNum = 0;
        });
      }

      // if(this.oldIntegralNum - Math.abs(this.integralNum)<0) {
      //     this.$nextTick(() => {
      //       this.integralNum = -this.oldIntegralNum
      //     });
      // }
    },
    // 提现设置
    async handleCashSet(row) {
      const { cashSet } = this;
      this.rowItem = row;
      const res = await AccountInfoApi.getAccountInfo({ userId: row.userId });
      if (res.data) {
        cashSet.info = res.data;
      } else {
        this.cashSet.info = this.$options.data().cashSet.info;
      }
      cashSet.show = true;
    },
    // 确认提现设置
    async confirmCashSet(val) {
      const {
        rowItem: { userId },
        cashSet,
      } = this;
      const params = {
        ...cashSet.info,
        userId,
      };
      cashSet.show = false;
      await AccountInfoApi.setAccountBase(params);
      this.$Utils.notifySuccess('设置成功');
    },
    handleClickEditor(row) {
      this.$router.push({ path: '/customer/customerAdd', query: { id: row.customerId } });
    },
    handleClickDetail(row) {
      this.$router.push({ path: '/customer/customerDetail', query: { id: row.customerId } });
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      let newStateName = row.state === 0 ? message.MSG_CONFIRM_ENABLE : message.MSG_CONFIRM_DISABLE;
      this.$confirm(newStateName, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.userId,
          // loginType: 1,
          state: currentState,
        };
        AuthApi.updateUserState(data).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.userId,
          state: -1,
        };
        AuthApi.deleteUser(data).then((res) => {
          this.listData();
          this.$Utils.notifySuccess();
        });
      });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.searchForm.userId = '';
      this.searchForm.minHealthPoints = '';
      this.searchForm.maxHealthPoints = '';
      this.onSearch();
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';

.m-b-10 {
  margin-bottom: 10px;
}
</style>
